/**
 * 工具函数库
 */

// 格式化时间
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

// 数字补零
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 获取附近有厕所的站点
const getNearbyToiletStations = (lineInfo, currentStationIndex) => {
  if (!lineInfo || !lineInfo.stations) return []
  
  const stations = lineInfo.stations
  const result = []
  
  // 向前查找
  for (let i = currentStationIndex - 1; i >= 0; i--) {
    if (stations[i].hasToilet) {
      result.push({
        ...stations[i],
        distance: currentStationIndex - i
      })
      break
    }
  }
  
  // 向后查找
  for (let i = currentStationIndex + 1; i < stations.length; i++) {
    if (stations[i].hasToilet) {
      result.push({
        ...stations[i],
        distance: i - currentStationIndex
      })
      break
    }
  }
  
  return result
}

// 获取站点在线路中的索引
const getStationIndexInLine = (lineInfo, stationId) => {
  if (!lineInfo || !lineInfo.stations) return -1
  
  return lineInfo.stations.findIndex(station => station.id === stationId)
}

module.exports = {
  formatTime,
  formatNumber,
  getNearbyToiletStations,
  getStationIndexInLine
}